from base.web import SHandler, get_files, BaseHandler, UserHandler

class create_bill(SHandler):
    def get_user(self):
        try:
            self.user = self.query_sql('select name, phone from hs_user where id = {0}'.format(self.get_argument('userid')))[0]
        except:
            res = self.res_error('insert')
            self.write(res)
            self.finish()
    def check_has(self):
        try:
            self.bill = self.query_sql('select money, current_money, userid from hs_total_bill where userid = {0}'.format(self.get_argument('userid')))[0]
        except:
            self.bill = dict(
                money = 0,
                current_money = 0,
                userid = 0
            )
    def make_params(self):
        create_list = ['userid', 'money', 'current_money']
        params = [
            '\'' + self.user['name'] + '\'',
            '\'' + self.user['phone'] + '\''
        ]
        create_list_s = ['userid', 'remark', 'money']
        params_s = []
        for key in create_list:
            if key == 'current_money':
                value = self.get_argument('money', False)
            else:
                value = self.get_argument(key, False)
            if not value and value != 0:
                self.res_error('insert')
                self.finish()
            else:
                params.append(value)
        for key in create_list_s:
            value = self.get_argument(key, False)
            print(value)
            if not value and value != 0:
                self.finish()
            else:
                if key == 'remark':
                    params_s.append('\'' + value + '\'')
                    continue
                params_s.append(value)
        self.condition = ','.join(params)
        self.condition_s = ','.join(params_s)
    def post(self):
        self.get_user()
        self.make_params()
        self.check_has()
        total_money = float(self.bill['money']) + float(self.get_argument('money')) #获取总借款
        current_money = float(self.bill['current_money']) + float(self.get_argument('money')) #获取未还借款数
        insert_bill_sql = '''
            INSERT INTO hs_bill (
                userid, remark, money
            ) VALUES ({0})
        '''.format(self.condition_s)
        update_total_sql = '''
            UPDATE hs_total_bill SET money = {0}, current_money = {1}
                WHERE userid = {2}
        '''.format(total_money, current_money, self.bill['userid'])
        insert_total_bill = '''
            INSERT INTO hs_total_bill (
                name, phone, userid, money, current_money
            ) VALUES ({0})
        '''.format(self.condition)
       
        if self.bill['userid']:  #更新数据
            sql_arr = [insert_bill_sql, update_total_sql]
        else: #新建数据
            sql_arr = [insert_bill_sql, insert_total_bill]
        if self.insert_sql(sql_arr):
            res = self.res_success('insert')
        else:
            res = self.res_error('insert')
        self.write(res)

class query_bill(SHandler):  #账单记录
    def make_params(self):
        current_page = int(self.get_argument('current_page', 1))
        page_size = int(self.get_argument('page_size', 10000))
        userid = int(self.get_argument('userid', 0))
        self.condition = dict(
            start = (current_page - 1) * page_size,
            num = page_size,
            useridq = ('= ' + str(userid)) if userid else '!= 0'
        )
    def post(self):
        self.make_params()
        try:
            data = self.query_sql('select * from hs_bill where userid {useridq} order by -ctime limit {start},{num}'.format(**self.condition))
            for d in data:
                d['ctime'] = str(d['ctime'])
            total = self.query_sql('select count(*) as total from hs_bill where userid {useridq} '.format(**self.condition))[0]['total']
            res = self.res_success('query', data = data, object = dict(total = total))
        except:
            res = self.res_error('query')
        finally:
            self.write(res)


class query_total_bill(SHandler):
    def make_params(self):
        name = self.get_argument('name')
        current_page = int(self.get_argument('current_page', 1))
        page_size = int(self.get_argument('page_size', 1000))
        self.condition = dict(
            name = name,
            start = (current_page - 1) * page_size,
            num = page_size,
        )

    def post(self):
        self.make_params()
        try:
            data = self.query_sql('select * from hs_total_bill where (name like \'%{name}%\' or phone like \'%{name}%\' ) limit {start},{num}'.format(**self.condition))
            for d in data:
                d['ctime'] = str(d['ctime'])
                if d['update_time']:
                    d['update_time'] = str(d['update_time'])
            total = self.query_sql('select count(*) as total from hs_total_bill where (name like \'%{name}%\' or phone like \'%{name}%\' )'.format(**self.condition))[0]['total']
            res = self.res_success('query', data = data, object = dict(total = total))
        except:
            res = self.res_error('query')
        finally:
            self.write(res)

class return_bill(SHandler):
    def get_money(self):
        self.bill = self.query_sql('select current_money, has_pay, userid from hs_total_bill where userid = {0}'.format(self.get_argument('userid')))[0]
    def make_params(self):
        return_list = ['userid', 'money', 'remark']
        params = []
        for k in return_list:
            value = self.get_argument(k, False)
            if k == 'remark':
                params.append('\'' + value + '\'')
            else:
                params.append(value)
        self.condition = ','.join(params)
    
    def post(self):
        self.make_params()
        self.get_money()
        money = float(self.get_argument('money'))
        userid = self.get_argument('userid')
        current_money = float(self.bill['current_money']) - money
        has_pay = float(self.bill['has_pay']) + money
        insert_hspay_sql = '''
            INSERT INTO hs_has_pay (
                userid, money, remark
            ) VALUES(
                {0}
            )
        '''.format(self.condition)
        update_total_sql = '''
            UPDATE hs_total_bill SET current_money = {0}, has_pay = {1}, money = {2} 
            WHERE userid = {3}
        '''.format(current_money, has_pay, current_money + has_pay, userid)
        if  current_money < 0:
            self.write(self.res_error('modify'))
            return
        else:
            if self.modify_sql([insert_hspay_sql, update_total_sql]):
                res = self.res_success('modify', message="还款成功")
            else:
                res = self.res_error('modify')
        self.write(res)
        
class query_return(SHandler):
    def post(self):
        userid = self.get_argument('userid')
        current_page = int(self.get_argument('current_page', 1))
        page_size = int(self.get_argument('page_size', 1000))
        condition = dict(
            userid = userid,
            start = (current_page - 1) * page_size,
            num = page_size
        )
        try:
            data = self.query_sql('select * from hs_has_pay where userid = {userid} order by -ctime limit {start},{num}'.format(**condition))
            for d in data:
                d['ctime'] = str(d['ctime'])
            total = self.query_sql('select count(*) as total from hs_has_pay where userid = {userid}'.format(**condition))[0]['total']
            res = self.res_success('query', data = data, object = dict(total = total))
        except:
            res = self.res_error('query')
        self.write(res)


bill_url = [
    (r'/api/bill/create_bill', create_bill),
    (r'/api/bill/query_bill', query_bill),
    (r'/api/bill/query_total_bill', query_total_bill),
    (r'/api/bill/return_bill', return_bill),
    (r'/api/bill/query_return', query_return),
]